package com.winchain.chainbill.receivables.biz.mod.service.impl;

import com.shell.bee.base.utils.DateUtil;
import com.shell.bee.base.utils.SystemUtil;
import com.shell.framework.utils.CommonDataUtil;
import com.winchain.chainbill.ChainBillUtil;
import com.winchain.chainbill.receivables.base.po.ArModification;
import com.winchain.chainbill.receivables.base.po.ArOperation;
import com.winchain.chainbill.receivables.base.po.ArRecord;
import com.winchain.chainbill.receivables.biz.mod.rx.ReceivablesModEvent;
import com.winchain.chainbill.receivables.biz.mod.rx.ReceivablesModSubscriber;
import com.winchain.chainbill.receivables.biz.mod.service.ReceivablesModService;
import java.math.BigDecimal;
import java.text.ParseException;
import org.springframework.stereotype.Service;
import rx.Observable;

@Service("receivablesModService")
public class ReceivablesModServiceImpl implements ReceivablesModService {
	private ReceivablesModSubscriber receivablesModSubscriber;

	public void mod(ArRecord arRecord) throws ParseException {
		ArModification mod = getModification(arRecord);
		ReceivablesModEvent event = new ReceivablesModEvent();
		event.setRec(arRecord);
		event.setMod(mod);

		ArOperation opt = new ArOperation();
		opt.setBizType("ar_mod");
		opt.setState(arRecord.getArState());
		opt.setOptCode("06");
		opt.setNextState("3");

		String limitDate = ChainBillUtil.getLimitDate("AR_MOD_REV_LIM_DATE");
		opt.setLimitDate(limitDate);
		opt.setRemark("������������");
		event.setOperation(opt);

		Observable<ReceivablesModEvent> observers = Observable.just(event);
		observers.subscribe(this.receivablesModSubscriber);
	}

	private ArModification getModification(ArRecord arRecord) {
		ArModification mod = new ArModification();
		BigDecimal arMoneyMod = arRecord.getArMoneyMod();
		BigDecimal pmtRatioMod = arRecord.getPmtRatioMod();
		String pmtDateMod = arRecord.getPmtDateMod();

		mod.setModId(SystemUtil.getUUID());
		mod.setArId(arRecord.getArId());
		mod.setArStateOrig(arRecord.getArState());
		if (arMoneyMod != null) {
			mod.setArMoney(arRecord.getArMoney());
			mod.setArMoneyMod(arMoneyMod);
		}
		if (pmtRatioMod != null) {
			mod.setPmtRatio(arRecord.getPmtRatio());
			mod.setPmtRatioMod(pmtRatioMod);
		}
		if (pmtRatioMod != null) {
			mod.setPmtDate(arRecord.getPmtDate());
			mod.setPmtDateMod(pmtDateMod);
		}
		mod.setModReason(arRecord.getModReason());
		mod.setModState("1");
		mod.setCreateTime(DateUtil.getSystemDateTime());
		mod.setCreatorId(CommonDataUtil.getUserId());
		mod.setOptSeq(arRecord.getOptSeq());
		return mod;
	}
}
